// pages/register/index.js
import WxValidate from '../../../utils/WxValidate'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mobile: '',
    code: '',
    password: '',
    passwordAgain: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initValidate()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  initValidate() {
    const rules = {
      mobile: {
        required: true,
        tel: true
      },
      code: {
        required: true,
        rangelength: [6, 6]
      },
      password: {
        required: true,
        rangelength: [5, 20]
      },
      passwordAgain: {
        required: true,
      }
    }
    const messages = {
      mobile: {
        required: '请输入手机号',
        tel: '输入正确手机号'
      },
      code: {
        required: '请输入短信验证码',
        rangelength: '请输入6位短信验证码'
      },
      password: {
        required: '请输入密码',
        rangelength: '密码长度在5到20之间'
      },
      passwordAgain: {
        required: '请输入确认密码'
      },
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  handleGetCode(event) {
    this.setData({
      code: event.detail.value,
    })
  },
  goUserName() {
    wx.redirectTo({
      url: '/pages/user/login/userName/index',
    })
  },
  doRegiser() {
    var {
      mobile,
      code,
      password,
      passwordAgain
    } = this.data
    if (!this.WxValidate.checkForm(this.data)) {
      const error = this.WxValidate.errorList[0];
      getApp().util.showToast(error.msg)
      return;
    }
    if (password !== passwordAgain) {
      getApp().util.showToast('两次输入的密码不一致')
      return
    }

    getApp().network.post(getApp().api.userRegister, {
      mobile: mobile,
      password: password,
      passwordAgain: passwordAgain,
      verificationCode: code,
      realName: '--',
      comeSourceEnum: 'MEMBER_COME_SOURCE_WX_MP'
    }).then(res => {
      wx.setStorageSync(getApp().constant.TOKEN, res)
      getApp().util.showToast("注册成功,登录中！")
      getApp().verifyLogin()
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/index/index',
        })
      }, 1000);
    }).catch(() => {})

  }
})